﻿using System;
using System.IO;
using System.Xml.Linq;
using Rosetta.Default.Net;

namespace Rosetta.Default.AddIns.Xml
{
    public sealed class XDocumentConverter : Converter
    {
        #region Constructors

        public XDocumentConverter()
            : base("XDocument Converter")
        {
            Category = "Xml";

            Add<WebAddress, XDocument>("FromAddress", FromAddress);
            Add<FileInfo, XDocument>("FromFile", FromFile, "file");
            Add<string, XDocument>("FromString", FromString, "xml");
        }

        #endregion

        #region Class Methods

        private static XDocument FromAddress(WebAddress address)
        {
            return XDocument.Load(address.Uri.AbsoluteUri);
        }

        private static XDocument FromFile([NotNull] FileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            using (var reader = file.OpenText())
            {
                return XDocument.Load(reader);
            }
        }

        private static XDocument FromString([NotNull] string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentNullException("xml");
            }

            return XDocument.Parse(xml);
        }

        #endregion
    }
}